<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <template #header>
      <el-form label-width="80px" :inline="true">
        <el-form-item label="用户名:">
          <el-input placeholder="请输入" v-model="username"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="ele-Search" @click="search"
            >搜索</el-button
          >
          <el-button type="primary" icon="ele-Plus" @click="clickAdd"
            >新增</el-button
          >
        </el-form-item>
      </el-form>
    </template>
    <el-table :data="userList" border stripe v-loading="loading">
      <el-table-column type="index" width="80" label="序号" />
      <el-table-column label="ID" prop="id" width="100"> </el-table-column>
      <el-table-column label="用户名" prop="username"> </el-table-column>
      <el-table-column label="角色列表" prop="roleName"> </el-table-column>
      <el-table-column label="创建时间" prop="createTime"> </el-table-column>
      <el-table-column label="更新时间" prop="updateTime"> </el-table-column>

      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-button type="success" size="default" @click="showRole(row.id)"
            >角色</el-button
          >
          <el-button type="primary" size="default" @click="edit(row)"
            >编辑</el-button
          >
          <el-button type="danger" size="default">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :style="{ marginTop: '20px' }"
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      layout="->,total, prev, pager, next, sizes ,jumper"
      :page-sizes="[20, 40, 80, 100]"
      :total="totalNum"
      background
      :pager-count="7"
    >
    </el-pagination>
  </el-card>

  <el-dialog
    :title="addUser.id ? '修改' : '新增'"
    v-model="showDialog"
    width="40%"
    top="60"
    :style="{ marginTop: '30px' }"
  >
    <el-form label-width="100px" :inline="false">
      <el-form-item label="用户名:">
        <el-input placeholder="请输入" v-model="addUser.username"></el-input>
      </el-form-item>
      <el-form-item label="密码:">
        <el-input placeholder="请输入" v-model="addUser.password"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="addOrEditUser">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <el-drawer v-model="showDrawer" title="权限配置">
    <template #header>
      <h2>权限配置</h2>
      <el-button type="primary" size="default" @click="seav">提交</el-button>
    </template>

    <template #default>
      <el-divider />
      <el-checkbox
        v-model="checkAll"
        :indeterminate="isIndeterminate"
        @change="handleCheckAllChange"
      >
        全选
      </el-checkbox>
      <el-divider />
      <el-checkbox-group
        v-model="assignRolesIdLIst"
        @change="handleCheckedCitiesChange"
      >
        <el-checkbox
          v-for="role in allRolesList"
          :key="role.id"
          :label="role.id"
          >{{ role.roleName }}</el-checkbox
        >
      </el-checkbox-group>
    </template>
  </el-drawer>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "User",
});
</script>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import {
  reqGetUserList,
  reqAddUserInfo,
  reqUpdateUserInfo,
  reqGetRoleInfo,
  reqSetRole,
} from "@/api/system/user";
import { ElMessage } from "element-plus";
import type {
  RoleListType,
  UserAddInfoType,
  UserListType,
} from "@/api/system/user/types";

// 初始化数据
const currentPage = ref(1);
const pageSize = ref(10);
const totalNum = ref(0);
const username = ref("");
const userList = ref<UserListType>([]);
const showDialog = ref(false);
const loading = ref(false);
const addUser = ref<UserAddInfoType>({
  id: null,
  username: "",
  password: "",
  name: "",
  roleName: "",
});

/**
 * 封装获取用户列表函数
 */
const getUserList = async (page: number = currentPage.value) => {
  try {
    loading.value = true;
    const res = await reqGetUserList(page, pageSize.value, username.value);
    userList.value = res.records;
    totalNum.value = res.total;
    loading.value = false;
  } catch (error: any) {
    ElMessage.error("请求数据失败:" + error.message);
  }
};

/**
 * 组件完成初始渲染时调用函数
 */
onMounted(() => {
  getUserList();
});

/**
 * 监听页码和条数的变化
 */
watch([currentPage, pageSize], () => {
  getUserList();
});

/**
 * 点击搜索
 */
const search = () => {
  getUserList(1);
};

/**
 * 点击新增
 */
const clickAdd = () => {
  showDialog.value = true;
  addUser.value = {
    id: null,
    username: "",
    password: "",
    name: "",
    roleName: "",
  };
};

/**
 * 点击修改
 */
const edit = (row: UserAddInfoType) => {
  showDialog.value = true;
  assignRolesIdLIst.value = [];
  addUser.value = row;
};

/**
 * 点击确定
 */
const addOrEditUser = async () => {
  if (addUser.value.id) {
    // 修改
    try {
      await reqUpdateUserInfo(addUser.value);
      ElMessage.error("修改成功!");
      getUserList();
    } catch (error: any) {
      ElMessage.error("修改失败:" + error.message);
    }
  } else {
    //添加
    try {
      await reqAddUserInfo(addUser.value);
      ElMessage.error("添加成功!");
      getUserList();
    } catch (error: any) {
      ElMessage.error("添加失败:" + error.message);
    }
  }
};

// 初始化用户的角色管理数据
const checkAll = ref(false);
const assignRoles = ref<RoleListType>([]);
const assignRolesIdLIst = ref<any>([]);
const allRolesList = ref<RoleListType>([]);
const isIndeterminate = ref(true);
const showDrawer = ref(false);
const editRoleId = ref(0);

/**
 * 点击设置角色按钮
 */
const showRole = async (id: number) => {
  try {
    showDrawer.value = true;
    editRoleId.value = id;
    const res = await reqGetRoleInfo(id);
    allRolesList.value = res.allRolesList;
    assignRoles.value = res.assignRoles;
    // assignRolesIdLIst.value.push(res.assignRoles.map((item) => item.id));
    res.assignRoles.forEach((item) => {
      assignRolesIdLIst.value.push(item.id);
    });
    console.log(assignRolesIdLIst.value, "id!!!!");

    assignRoles.value = res.assignRoles;
    console.log(res);
  } catch (error: any) {
    ElMessage.error("获取角色信息失败:" + error.message);
  }
};
/**
 * 点击全选
 * @param val
 */
const handleCheckAllChange = (val: string | number | boolean): any => {
  assignRoles.value = val ? allRolesList.value : [];
  isIndeterminate.value = false;
};

/**
 * 多选框的单选事件
 */
const handleCheckedCitiesChange = (value: string[]): any => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === allRolesList.value.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < allRolesList.value.length;
  assignRolesIdLIst.value = value;
};

/**
 * 点击提交按钮
 */
const seav = async () => {
  try {
    await reqSetRole(editRoleId.value, assignRolesIdLIst.value);
    ElMessage.success("设置成功");
    showDrawer.value = false;
    getUserList();
  } catch (error: any) {
    ElMessage.error("设置失败:" + error.message);
  }
};
</script>

<style scoped></style>
